package com.seeyon.apps.wpscoordination.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seeyon.apps.wpscoordination.dto.*;
import com.seeyon.apps.wpscoordination.service.ISendMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SendMessageServiceImpl implements ISendMessageService {
    @Value("${wps.messageUrl}")
    private String messageUrl;
    @Value("${wps.appId}")
    private String appId;
    @Value("${wps.secretKey}")
    private String secretKey;
    @Value("${wps.companyTokenUrl}")
    private String companyTokenUrl;

    @Override
    public Boolean SendCardTextUrlMessage(CardTextUrlMessageDto dto) throws Exception {
        // 获取当前日期
        Date date = new Date();
        // 创建RFC1123格式的日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        // 设置请求头类型
        String contentType = "application/json";
        // 获取 签名中的URL
        String companyUrl = companyTokenUrl.substring(companyTokenUrl.indexOf("/oauthapi")) + "?app_id=" + appId;
        // 格式化时间
        String formatDate = sdf.format(date);
        // 计算空字符 md5 转换成 16进制
        String contentMD5 = DigestUtil.md5Hex("");
        // 计算签名 sign部分
        String sha1Result = DigestUtil.sha1Hex(secretKey.toLowerCase() + contentMD5 + companyUrl + contentType + formatDate);
        String companyXAuth = "WPS-3:" + appId + ":" + sha1Result;

        //  获取 company_token
        Map<String, String> header = new HashMap<>();
        header.put("Content-type", contentType);
        header.put("Content-Md5", contentMD5);
        header.put("Date", formatDate);
        header.put("X-Auth", companyXAuth);

        log.info("开始请求companyToken====={}",new Date().getTime());
        //  发送请求 获取 company_token
        String body = HttpRequest.get(companyTokenUrl + "?app_id=" + appId).addHeaders(header).execute().body();
        ResponseDto responseDto = new ObjectMapper().readValue(body, ResponseDto.class);
        log.info("请求companyToken结束====={}",new Date().getTime());

        // 发送消息
        if (responseDto.getCompany_token() != null && responseDto.getResult() == 0) {
            formatDate = sdf.format(new Date());
            // 设置消息体
            CardMessageHrefDto cardMessageHref=new CardMessageHrefDto();
            cardMessageHref.setUrl(dto.getHrefUrl());
            cardMessageHref.setText("打开消息链接");
            cardMessageHref.setStyle("normal");
            cardMessageHref.setDisable(false);
            cardMessageHref.setPlatform_url(new PlatformUrlDto(dto.getHrefUrl(),dto.getHrefUrl(),dto.getHrefUrl()));

            CardUrlMessageContentDto cardUrlMessageContent=new CardUrlMessageContentDto();
            cardUrlMessageContent.setType(2);
            cardUrlMessageContent.setTitle(dto.getMessageTitle());
            cardUrlMessageContent.setBody(dto.getMessage());
            cardUrlMessageContent.setHref(cardMessageHref);

            UserDto users = new UserDto();
            String[] userIds={"l5xWkA2VooXoMDE"};
            users.setCompany_uids(userIds);
            users.setCompany_id("pEPDeMMDE");

            SendMessageDto sendMessageDto =   SendMessageDto.builder().app_key(appId).msg_type(1)
                    .content(cardUrlMessageContent).to_users(users).utype(0).msg_type(2).company_uid("R8loNdO5NzQoMDE").company_id("pEPDeMMDE").build();


            // 转换消息体为json  设置发送请求头
            String bodyJson = new ObjectMapper().writeValueAsString(sendMessageDto);
            contentMD5 = DigestUtil.md5Hex(bodyJson);
            String messageUtl = messageUrl.substring(messageUrl.indexOf("/kopen")) + "?company_token=" + responseDto.getCompany_token();
            sha1Result = DigestUtil.sha1Hex(secretKey.toLowerCase() + contentMD5 + messageUtl + contentType + formatDate);
            companyXAuth = "WPS-3:" + appId + ":" + sha1Result;

            // 设置发送头
            header.clear();
            header.put("Content-type", contentType);
            header.put("Content-Md5", contentMD5);
            header.put("Date", formatDate);
            header.put("X-Auth", companyXAuth);

            // 发送请求 发送消息
            log.info("发送消息请求开始====={}",new Date().getTime());
            String sendMessageBody = HttpRequest.post(messageUrl + "?company_token=" + responseDto.getCompany_token()).addHeaders(header).body(bodyJson).execute().body();
            log.info("发送消息请求结束====={}",new Date().getTime());
            responseDto = new ObjectMapper().readValue(sendMessageBody, ResponseDto.class);

            if (responseDto.getResult() == 0) {
                log.info("发送成功,发送者为====={},内容为======{}",sendMessageDto.getCompany_uid(),dto.getMessage());
                return true;
            } else {
                log.info("发送失败,发送者为====={},失败原因为======={}",sendMessageDto.getCompany_uid(),responseDto.getMessage_id());
                return false;
            }
        }else {
            log.info("获取companyToken失败,发送者为====={},失败内容为====={}",dto.getCompanyUid(),responseDto.toString());
            return false;
        }
    }

}
